const CITIES = {
  "北京": {
    "_value_": ["北京"],
    "北京": ["昌平区", "朝阳区", "大兴区", "东城区", "房山区", "丰台区", "海淀区", "门头沟区", "密云区", "平谷区", "石景山区", "顺义区", "通州区", "西城区", "怀柔区"]
  },
  "天津": {
    "_value_": ["天津"],
    "天津": ["宝坻区", "滨海新区", "河东区", "河西区", "红桥区", "蓟州区", "静海区", "南开区", "武清区", "西青区"]
  },
  "河北": {
    "_value_": ["石家庄", "保定", "沧州", "承德", "邯郸", "衡水", "廊坊", "秦皇岛", "唐山", "邢台", "张家口", "辛集", "新乐", "晋州"],
    "石家庄": ["平山县", "桥西区", "新华区", "裕华区", "长安区"],
    "保定": ["定州市", "竞秀区", "莲池区", "涿州市"],
    "沧州": ["河间市", "黄骅市", "青县", "任丘市", "肃宁县", "运河区"],
    "承德": ["双桥区"],
    "邯郸": ["丛台区", "邯山区", "曲周县"],
    "衡水": ["安平县", "桃城区"],
    "廊坊": ["安次区", "霸州市", "大厂县", "固安县", "广阳区", "三河市", "香河县", "燕郊镇"],
    "秦皇岛": ["海港区"],
    "唐山": ["曹妃甸区", "路北区", "路南区", "迁安市", "遵化市"],
    "邢台": ["隆尧县", "桥西区"],
    "张家口": ["桥东区"],
    "辛集": [],
    "新乐": [],
    "晋州": []
  },
  "山西": {
    "_value_": ["太原", "长治", "大同", "晋城", "晋中", "临汾", "吕梁", "阳泉", "运城"],
    "太原": ["万柏林区", "小店区", "迎泽区"],
    "长治": ["潞州区"],
    "大同": ["平城区"],
    "晋城": ["城区"],
    "晋中": ["介休市", "榆次区"],
    "临汾": ["侯马市", "尧都区"],
    "吕梁": ["离石区"],
    "阳泉": ["郊区"],
    "运城": ["盐湖区"]
  }
};

const BASE_URL = 'https://api.daikin1995.com';

const ENDPOINTS = {
  config: '/daikin/landing-page/config',
  submit: '/daikin/landing-page/enroll',
  code: '/daikin/landing-page/code',
};

const isValidPhone = phone => /^1[3456789]\d{9}$/.test(phone);
let counterId = null;

Page({
  data: {
    // 自定义渠道
    customSource: null,

    // 系统信息
    system: wx.getSystemInfoSync(),

    // 是否已加载配置
    loaded: false,

    // 头部图片
    head: null,

    // 主体图片
    body: null,

    // 底部固定按钮
    button: null,

    // 提交按钮 - 1
    button1: null,

    // 表单标题 - 1
    title1: null,

    // 提交按钮 - 2
    button2: null,

    // 表单标题 - 2
    title2: null,

    // 提交成功的提示
    enrollmentMsg: null,

    // 地区选择
    addressPicker: [
      ['北京', '天津', '河北', '山西'],
      ['北京'],
      CITIES['北京']['北京'],
    ],

    // 表单--姓名
    name: null,

    // 表单--手机号
    phone: null,

    // 验证码
    code: null,

    // 表单--已选择的地址
    chosenAddress: [],

    // 屏幕高度
    screenHeight: wx.getSystemInfoSync().windowHeight,

    // 页面已滚动距离
    offsetTop: 0,

    // 倒计时
    counter: 60,

    // 广告投放
    gdt_vid: '',
    weixinadinfo: '',
  },

  /**
   * 页面加载
   */
  onLoad: function (options) {
    const {
      customSource,
      gdt_vid,
      weixinadinfo,
    } = options;

    if (customSource) {
      this.setData({
        customSource,
        gdt_vid,
        weixinadinfo,
      });
    }

    wx.request({
      url: `${BASE_URL}${ENDPOINTS.config}`,
      data: {
        id: options.id || 2,
      },
      success: res => {
        const {
          data,
          errMsg,
        } = res;

        if (errMsg === 'request:ok') {
          const {
            imgHead,
            imgBody,
            title1,
            button1,
            title2,
            button2,
            buttonMain,
            enrollmentMsg,
          } = data.result;

          return this.setData({
            loaded: true,
            head: imgHead,
            body: imgBody,
            button: buttonMain,
            title1,
            button1,
            title2,
            button2,
            buttonMain,
            enrollmentMsg,
          });
        }

        wx.showToast({
          title: '无法加载页面信息',
        });
      },
      fail: function () {
        wx.showToast({
          title: '无法加载页面信息',
        });
      }
    });
  },

  onPageScroll: function (e) {
    this.setData({
      offsetTop: e.scrollTop,
    });
  },

  /**
   * 设置地址
   */
  onAddressChange: function (e) {
    this.setData({
      chosenAddress: e.detail.value,
    });
  },

  /**
   * 地址选择
   */
  onAddressColumnChange: function (e) {
    const {
      column,
      value,
    } = e.detail;

    let {
      addressPicker,
      chosenAddress,
    } = this.data;

    if (chosenAddress.length === 0) {
      chosenAddress = [0, 0, 0];
    }

    var data = {
      addressPicker,
      chosenAddress,
    };

    data.chosenAddress[column] = value;

    switch (column) {
      case 0:
        data.addressPicker[1] = CITIES[addressPicker[0][value]]._value_;
        data.addressPicker[2] = CITIES[addressPicker[0][value]][data.addressPicker[1][0]];
        data.chosenAddress[1] = 0;
        data.chosenAddress[2] = 0;
        break;
      case 1:
        data.addressPicker[2] = CITIES[addressPicker[0][chosenAddress[0]]][addressPicker[1][value]];
        data.chosenAddress[2] = 0;
        break;
    }

    this.setData(data);
  },

  /**
   * 提交信息
   */
  onSubmit: function () {
    const {
      customSource,
      system,
      name,
      phone,
      code,
      addressPicker,
      chosenAddress,
      enrollmentMsg,
      gdt_vid,
      weixinadinfo,
    } = this.data;

    if (!name) {
      return wx.showModal({
        content: '请填写姓名',
        showCancel: false,
      });
    }

    if (!phone) {
      return wx.showModal({
        content: '请填写手机号',
        showCancel: false,
      });
    }

    if (!isValidPhone(phone)) {
      return wx.showModal({
        content: '手机号不合法',
        showCancel: false,
      });
    }

    if (!code) {
      return wx.showModal({
        content: '请输入验证码',
        showCancel: false,
      });
    }

    if (chosenAddress.length !== 3) {
      return wx.showModal({
        content: '请选择所在地址',
        showCancel: false,
      });
    }

    wx.request({
      url: `${BASE_URL}${ENDPOINTS.submit}`,
      method: 'POST',
      data: {
        name,
        phone,
        address: [addressPicker[0][chosenAddress[0]], addressPicker[1][chosenAddress[1]], addressPicker[2][chosenAddress[2]]].join('/'),
        code,
        source: customSource || system.platform,
        ...gdt_vid && {
          gdt_vid,
        },
        ...weixinadinfo && {
          weixinadinfo
        },
      },
      success: function (res) {
        const {
          data,
          errMsg,
        } = res;
        if (errMsg === 'request:ok') {
          if (data.success) {
            return wx.showModal({
              title: '预约成功',
              content: enrollmentMsg || '您已成功预约，工作人员将会尽快与您取得联系，请您保持电话畅通！',
              showCancel: false,
            });
          }
          return wx.showModal({
            content: data.msg || '提交表单时遇到问题，请稍后重试！',
            showCancel: false,
          });
        }
        wx.showModal({
          title: '提交失败',
          content: '暂时无法处理您的请求，请稍后重试！',
          showCancel: false,
        });
      },
      fail: function () {
        wx.showModal({
          title: '提交失败',
          content: '暂时无法处理您的请求，请稍后重试！',
          showCancel: false,
        });
      },
    });
  },

  onInput: function (event) {
    this.setData({
      [event.currentTarget.id]: event.detail.value,
    });
  },

  goToForm: function () {
    const {
      screenHeight,
      offsetTop,
    } = this.data;

    const query = wx.createSelectorQuery();
    query.select(offsetTop > (screenHeight + 200) ? '#bottom-form' : '#top-form').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(resp => {
      wx.pageScrollTo({
        scrollTop: resp[0].top + resp[1].scrollTop,
        duration: 300,
      });
    });
  },

  getCode: function () {
    const {
      phone,
    } = this.data;

    if (!isValidPhone(phone)) {
      return wx.showModal({
        content: '请输入正确的手机号',
        showCancel: false,
      });
    }

    this.setData({
      counter: 59,
    }, () => {
      counterId = setInterval(() => {
        let {
          counter,
        } = this.data;

        if (counter == 1) {
          clearInterval(counterId);
          counterId = null;
          counter = 61;
        }

        this.setData({
          counter: counter - 1,
        });
      }, 1000);
    });

    wx.request({
      url: `${BASE_URL}${ENDPOINTS.code}`,
      data: {
        phone,
      },
      success: result => {
        if (result.errMsg === 'request:ok' && result.data.success) {
          wx.showToast({
            title: '验证码已发送',
          });
        } else {
          wx.showToast({
            title: '无法获取验证码',
          });
          clearInterval(counterId);
          counterId = null;
          this.setData({
            counter: 60,
          });
        }
      },
      fail: function () {
        wx.showToast({
          title: '无法获取验证码',
          icon: 'none',
        });
        clearInterval(counterId);
        counterId = null;
        this.setData({
          counter: 60,
        });
      },
    });
  },

})
